#!/bin/sh

main() {
 local HOSTS="$@"
 if [ $# -eq 0 ] ;then
  echo "list hosts to watch as arguments" >&2
  exit 1
 fi
 TRAPS="1 2 3 15"
 local T=`mktemp`
 local WRETRY=10
 local WAGAIN=50
 set_trap "rm -f $T"
 mk_b1b2
 while true ;do
  sleep $WRETRY
  date
  for HOST in $HOSTS ;do
   if
    net_down
   then
    echo "network down, retry"
    continue
   fi
   printf "$HOST "
   if
    ping -q -c1 -w5 $HOST 2>/dev/null >"$T" #TODO stderr...
   then
    echo "ok"
   else
    if
     net_down
    then
     echo "network down, retry"
     continue
    else
     echo "fail"
     grep -v "^ *$" "$T" |
     sed "s~^~ ~"
     make_noise
    fi
   fi
  done
  sleep $WAGAIN
 done
}

net_down() {
# local HOST=`route | grep "^default" | tr -s " " | cut -f 2 -d " "`
 local HOST=bkil.hu
 ! pingerr $HOST
}

pingerr() {
 ping -q -c1 -w5 "$@" 2>/dev/null >/dev/null #TODO refactor from above
}

make_noise() {
    noise1
    noise1
    noise2
    noise2
}

mk_b1b2() {
 B1=`mktemp`
 nice seq 1 1500 > $B1 ||exit 1
 B2=`mktemp`
 nice seq 1500 -1 1 > $B2 ||exit 1
 set_trap "rm -f $B1 $B2"
}

noise1(){
    playsound $B1
}

noise2() {
    playsound $B2
}

playsound() {
    nice aplay "$@" >/dev/null 2>/dev/null
}

set_trap() {
#    return #TODO
 if [ -z "$TRAPH" ] ;then
  TRAPH=":"
 fi
 TRAPH="$TRAPH ; $@"
 trap "$TRAPH ;\
       trap - $TRAPS;\
       exit" $TRAPS
}

main "$@"
